package vn.njai.thousand_english_word.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import vn.njai.thousand_english_word.R;
import vn.njai.thousand_english_word.Utils.DataManager;

/**
 * Created by VUONG on 12/25/2014.
 */
public class LoadingActivity extends ActionBarActivity implements DataManager.LoadingListener{
    private String TAG = "LoadingActivity";
    @InjectView(R.id.txtInfo) public TextView mInfoText;
    @InjectView(R.id.txtProgress) public TextView mProgressText;
    private boolean mMustGuild = false;

    public static void start(Context context) {
        Intent intent = new Intent(context,LoadingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_activity);
        ButterKnife.inject(this);
        Handler handler = new Handler();
        DataManager.getInstance().mContext = this;
        DataManager.getInstance().init();
        DataManager.getInstance().setListener(this);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData();
            }
        },1000);
    }

    private void loadData() {
        if (DataManager.getInstance().isLoadFromFile() == false) {
            mInfoText.setText("Nạp dữ liệu lần đầu...");
            mMustGuild = true;
        }else {
            mInfoText.setText("Nạp dữ liệu...");
            mMustGuild = false;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (DataManager.getInstance().isLoadFromFile() == false) {
                    DataManager.getInstance().loadDataFromFile();
                }
                startApplication();
            }
        }).start();
    }

    private void startApplication(){
        if(mMustGuild){
            GuildActivity.start(getApplicationContext(),true);
        }else
            MainActivity.start(getApplicationContext());
        finish();
    }

    @Override
    public void onProgress(final int progress) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressText.setText(100*progress/DataManager.getInstance().mWordCount+ "%");
                mProgressText.requestLayout();
            }
        });

    }

    @Override
    public void onLoadDetailComplete() {

    }
}
